﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace Test
{

	internal class ProviderFinder : ExpressionVisitor
	{
		IQueryProvider provider;
		public static IQueryProvider Find(Expression expression) {
			var finder = new ProviderFinder();
			finder.Visit(expression);
			return finder.provider;
		}
		protected override Expression VisitConstant(ConstantExpression node) {
			Type elementType;
			if (this.IsQuery(node, out elementType)) {
				IQueryProvider @provider = ((IQueryable)node.Value).Provider;
				this.provider = (IQueryProvider)@provider;
			}
			return base.VisitConstant(node);
		}
	}

}
